package com.zl.basis.http;


import com.zl.basis.util.StringUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

public class DownloadUtil {
    private volatile static OkHttpClient mClient;

    public static OkHttpClient getClient() {
        if (null == mClient) {
            synchronized (OkHttpClient.class) {
                if (null == mClient) {
                    OkHttpClient.Builder builder = new OkHttpClient.Builder();
                    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
                    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
                    builder.addInterceptor(loggingInterceptor);
                    mClient = builder.build();
                }
            }
        }
        return mClient;
    }


    /**
     * @param url      下载连接
     * @param saveDir  储存下载文件的SDCard目录
     */
    public static boolean download(String url, String saveDir, String fileName) {
        Request request = new Request.Builder().url(url).build();
        try {
            Response response = getClient().newCall(request).execute();
            if (request != null) {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                String savePath = isExistDir(saveDir);
                try {
                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    File file = new File(savePath, StringUtil.isEmpty(fileName) ? getNameFromUrl(url) : fileName);
                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
//                        int progress = (int) (sum * 1.0f / total * 100);
                        // 下载中
                    }
                    fos.flush();
                    // 下载完成
                    return true;
                } catch (Exception e) {
                    return false;
                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException e) {
                    }
                    try {
                        if (fos != null)
                            fos.close();
                    } catch (IOException e) {
                    }
                }
            }


        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * @param url      下载连接
     * @param saveDir  储存下载文件的SDCard目录
     * @param listener 下载监听
     */
    public static void download(String url, String saveDir, String fileName, OnDownloadListener listener) {
        Request request = new Request.Builder().url(url).build();
        getClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                listener.onDownloadFailed(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                String savePath = isExistDir(saveDir);
                try {
                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    File file = new File(savePath, StringUtil.isEmpty(fileName) ? getNameFromUrl(url) : fileName);
                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                        // 下载中
                        listener.onDownloading(progress);
                    }
                    fos.flush();
                    // 下载完成
                    listener.onDownloadSuccess(file.getAbsolutePath());
                } catch (Exception e) {
                    listener.onDownloadFailed(e);
                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException e) {
                    }
                    try {
                        if (fos != null)
                            fos.close();
                    } catch (IOException e) {
                    }
                }
            }
        });
    }

    /**
     * @param saveDir
     * @return
     * @throws IOException 判断下载目录是否存在
     */
    private static String isExistDir(String saveDir) throws IOException {
        // 下载位置
//        File downloadFile = new File(Environment.getExternalStorageDirectory(), saveDir);
//        if (!downloadFile.mkdirs()) {
//            downloadFile.createNewFile();
//        }
//        String savePath = downloadFile.getAbsolutePath();
        File downLoadFile = new File(saveDir);
        if (!downLoadFile.exists()) {
            downLoadFile.mkdirs();
        }
        return saveDir;
    }

    /**
     * @param url
     * @return 从下载连接中解析出文件名
     */
    private static String getNameFromUrl(String url) {
        return url.substring(url.lastIndexOf("/") + 1);
    }


}
